import React, { memo, useEffect, useState } from 'react';
import { message, Spin } from 'antd';

import { queryChartData } from '@/services/salaryManage/salaryChart';
import { isSuccess } from '@/utils/request';

import SalaryChart from './SalaryChart';
import ChartWrapper from './ChartWrapper'


import useMyChartSetting from '../hooks/useMyChartSetting';
import { isEmptyObj } from '../paramMap';

const MyChartWrapper = memo(({ title, organizationCode, chartConfig, ...otherProps }) => {
    const [chartParam, setChartParam] = useState({})
    const [chartData, setChartData] = useState([])
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        setChartParam(JSON.parse(JSON.stringify(chartConfig)))
    }, [chartConfig])

    useEffect(() => {
        const queryChartFn = async () => {
            setLoading(true)
            const chartRequest = await queryChartData({
                ...chartParam,
                organizationCode
            })
            setLoading(false)
            if (isSuccess(chartRequest)) {
                setChartData(chartRequest.data || [])
            } else {
                console.warn(chartParam)
                message.error(`${chartRequest.msg}`)
            }
        }

        if (!isEmptyObj(chartParam)) {
            queryChartFn()
        }
        return () => {
            setChartData([])
        }
    }, [chartParam])

    // 改变配置参数
    const changeConfigHandle = val => {
        setChartParam({
            ...chartParam,
            ...val
        })
    }

    const { render: renderSettingWrapper } = useMyChartSetting(chartParam, organizationCode, changeConfigHandle);

    return (
        <Spin spinning={loading}>
            <ChartWrapper title={title} settingWrapper={renderSettingWrapper()} {...otherProps}>
                <SalaryChart chartData={chartData} chartParam={chartParam} loading={loading}/>
            </ChartWrapper>
        </Spin>
    )
})

export default MyChartWrapper
